﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace SweetSurvey.Models.Repositories
{
    public class OptionRepository: RepositoryBase, IOptionRepository
    {
        public Option Get(string id, bool detaching = true)
        {
            var context = new SweetSurveyModelContainer();
            var entity = context.Options.Where(e => e.Id == id).Single();
            if (detaching) { context.Detach(entity); }
            return entity;
        }

        public string Create(Option entity)
        {
            if (string.IsNullOrEmpty(entity.Id))
                entity.Id = RepositoryBase.GenerateRandomId();
            var context = new SweetSurveyModelContainer();
            context.Options.AddObject(entity);
            context.SaveChanges();
            return entity.Id;
        }

        public void Update(Option entity)
        {
            RepositoryBase.Update(entity);
        }

        public void Delete(string id)
        {
            RepositoryBase.Delete(Get(id));
        }

        public IQueryable<Option> GetOptionsByQuestionId(string questionId)
        {
            var context = new SweetSurveyModelContainer();
            var entities = from e in context.Options
                           where e.QuestionId == questionId
                           orderby e.Index ascending
                           select e;
            return entities;
        }

        public void DeleteOptionsByQuestionId(string questionId)
        {
            var context = new SweetSurveyModelContainer();
            var entities = context.Options.Where(e => e.QuestionId == questionId);
            foreach (var entity in entities)
            {
                context.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted);
            }
            context.SaveChanges();
        }

        public void CreateOptionsByQuestionId(string questionId, IList<string> options)
        {
            var context = new SweetSurveyModelContainer();
            for (short i = 0; i < options.Count; i++)
            {
                var option = options[i];
                context.Options.AddObject(new Option()
                {
                    Id = RepositoryBase.GenerateRandomId(),
                    QuestionId = questionId,
                    Text = option,
                    Index = i
                });
            }
            context.SaveChanges();
        }
    }
}